import * as THREE from 'three'
import { RectAreaLightHelper } from 'three/examples/jsm/helpers/RectAreaLightHelper.js'
import { RectAreaLightUniformsLib } from 'three/examples/jsm/lights/RectAreaLightUniformsLib.js'
import createApp from '../../core'

function createRectAreaLight (dom: HTMLElement) {
  const { camera, scene, gui } = createApp(dom)
  camera.position.set(-120, 80, 120)
  camera.lookAt(scene.position)

  const axes = new THREE.AxesHelper(100)
  scene.add(axes)

  const { ambientColor, ambientIntensity, color, intensity, width, height, x, y, z } = data
  const ambient = new THREE.AmbientLight(ambientColor, ambientIntensity)
  scene.add(ambient)

  // 平面光必须加上这个,且平面光只支持MeshPhysicalMaterial和MeshStandardMaterial属性
  RectAreaLightUniformsLib.init()
  const rectAreaLight = new THREE.RectAreaLight(color, intensity, width, height)
  rectAreaLight.position.set(x, y, z)
  rectAreaLight.lookAt(0, 0, 0)
  scene.add(rectAreaLight)

  const helper = new RectAreaLightHelper(rectAreaLight)
  scene.add(helper)

  const planeGeometry = new THREE.PlaneGeometry(200, 200)
  const material = new THREE.MeshStandardMaterial({ color: 0xffffff })
  const plane = new THREE.Mesh(planeGeometry, material)
  plane.rotateX(-Math.PI / 2)
  scene.add(plane)

  const boxGeometry = new THREE.BoxGeometry(30, 30, 30)
  const boxMaterial = new THREE.MeshStandardMaterial({ color: 0x0000ff })
  const box = new THREE.Mesh(boxGeometry, boxMaterial)
  scene.add(box)

  const folder1 = gui.addFolder('环境光参数')
  folder1.addColor(data, 'ambientColor').onChange(() => {
    ambient.color = new THREE.Color(data.ambientColor)
  })
  folder1.add(data, 'ambientIntensity', 0, 10).onChange(() => {
    ambient.intensity = data.ambientIntensity
  })

  const folder2 = gui.addFolder('点光源参数')
  folder2.addColor(data, 'color').onChange(() => {
    rectAreaLight.color = new THREE.Color(data.color)
  })
  folder2.add(data, 'intensity', 0, 10).onChange(() => {
    rectAreaLight.intensity = data.intensity
  })
  folder2.add(data, 'width', 0, 100).onChange(() => {
    rectAreaLight.width = data.width
  })
  folder2.add(data, 'height', 0, 100).onChange(() => {
    rectAreaLight.height = data.height
  })

  const folder3 = gui.addFolder('点光源位置')
  folder3.add(data, 'x', -100, 100).onChange(() => {
    rectAreaLight.position.x = data.x
    rectAreaLight.lookAt(0, 0, 0)
  })
  folder3.add(data, 'y', -100, 100).onChange(() => {
    rectAreaLight.position.y = data.y
    rectAreaLight.lookAt(0, 0, 0)
  })
  folder3.add(data, 'z', -100, 100).onChange(() => {
    rectAreaLight.position.z = data.z
    rectAreaLight.lookAt(0, 0, 0)
  })
}

const data = {
  ambientColor: 0xb2aeae,
  ambientIntensity: 1,
  color: 0x3dd6a3,
  intensity: 7,
  width: 30,
  height: 30,
  x: 0,
  y: 40,
  z: 0
}

export {
  createRectAreaLight
}
